package de.lmu.mvs.lerngruppenfinder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.beardedhen.androidbootstrap.BootstrapCircleThumbnail;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

import de.lmu.mvs.lerngruppenfinder.interests.InterestNode;
import de.lmu.mvs.lerngruppenfinder.interests.InterestTree;
import de.lmu.mvs.lerngruppenfinder.utils.ApplicationController;
import de.lmu.mvs.lerngruppenfinder.utils.BaseActivity;
import de.lmu.mvs.lerngruppenfinder.utils.Constants;
import de.lmu.mvs.lerngruppenfinder.utils.FileApi;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector.ServerConnectorListener;
import de.lmu.mvs.lerngruppenfinder.utils.ServerConnector.ServerError;
import de.lmu.mvs.lerngruppenfinder.widget.ExpandablePanel;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShowUserProfileActivity extends BaseActivity {

	private static final String TAG = UserProfileActivity.class.getSimpleName();



	//private ImageView pPic;	
	private BootstrapCircleThumbnail pPic;

	private TextView nameText;


	private TextView emailE;

	private int userID;

	boolean clicked = false;
	boolean nameChanged = false;
	String oldName;


	private LinearLayout mInterestContainer;
	private InterestTree mInterestTree;
	
	/** 
	 * map keeps separate interest arrays for each created view.
	 * Is used to determine which interests have changed after an edit.
	 */
	HashMap<Integer, List<Integer>> mUserInterestsMap = new HashMap<Integer, List<Integer>>();

	/** all interests that the user has */
	private List<Integer> mUserInterests = new ArrayList<Integer>();

	private boolean mUserInteractionVisible = false;
	private boolean mPasswordEditVisible = false;

	// FIXME compare user name in edittext with user name from json
	boolean firstEdit = true;
	TextView button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB){
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		setContentView(R.layout.activity_show_user);

		Intent intent = getIntent();
		userID = intent.getIntExtra("id", 0);

		((TextView)findViewById(R.id.contact)).setTypeface(ApplicationController.getTypeFace());

		// show save bar when password is correct

		nameText = (TextView) findViewById(R.id.nameDisplay);
		emailE = (TextView) findViewById(R.id.emailDisplay);
		pPic = (BootstrapCircleThumbnail) findViewById(R.id.pPicView);
		ServerConnector.getUserById(new ServerConnectorListener<JsonObject>() {

			@Override
			public void requestFinished(JsonObject json) {
				nameText.setText(json.get("name").asString());
				emailE.setText(json.get("mail").asString());
				ImageLoader imageLoader = ApplicationController.getInstance().getImageLoader();
				final String url1 = json.get("bild").asString();							
				imageLoader.get(url1, new ImageLoader.ImageListener() {
			        
					@Override
			        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
						if(response.getBitmap() != null){
							pPic.setImage(response.getBitmap());
						} else {
							Log.e(TAG, "No image found at " + url1);
						}
						
			        }

			        @Override
			        public void onErrorResponse(VolleyError error) {
			        	Log.e(TAG, error.getLocalizedMessage());
			        }
			    });
			}

			@Override
			public void requestError(ServerError error) {
				// TODO Auto-generated method stub
				
			}
		}, userID);
		setupInterests();
		
		
		button = (TextView) findViewById(R.id.contact);
		button.setOnClickListener(new OnClickListener() {
			 
			@Override
			public void onClick(View arg0) {
 
				// get prompts.xml view
				LayoutInflater li = LayoutInflater.from(ShowUserProfileActivity.this);
				View promptsView = li.inflate(R.layout.prompt, null);
 
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ShowUserProfileActivity.this);
 
				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);
				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextDialogUserInput);
 
				// set dialog message
				alertDialogBuilder
					.setCancelable(false)
					.setPositiveButton("OK",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						// get user input and set it to result
						// edit text
					    ServerConnector.contactUser(new ServerConnectorListener<JsonObject>() {

							@Override
							public void requestFinished(JsonObject json) {
								Toast.makeText(getBaseContext(), "Deine Nachricht wurde versendet", Toast.LENGTH_SHORT).show();
							}

							@Override
							public void requestError(ServerError error) {
								// TODO Auto-generated method stub
								
							}
						}, FileApi.readLoginCredentials().id, userID, userInput.getText().toString());

					    }
					  })
					.setNegativeButton("Cancel",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					    }
					  });
 
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();
 
			}
		});
	}
	
	private void setupInterests(){
		mInterestContainer = (LinearLayout) findViewById(R.id.interest_container);

		//FIXME get user id and request user interests from server
		ServerConnector.getUserInterests(new ServerConnectorListener<JsonArray>() {

			@Override
			public void requestFinished(JsonArray json) {
				if(json.isArray()){
					mUserInterests.clear();
					for (int i = 0; i < json.size(); i++) {
						mUserInterests.add(Integer.parseInt(
								json.asArray().get(i).asObject().get(Constants.JSON_INTEREST_ID).asString()));
					}
					// if the other one finished first, create interest text views
					if(mInterestTree != null){
						createInterestViews();
					}
				}
			}
			@Override
			public void requestError(ServerError error) {
				Log.e(TAG, error.getErrorMessage());
			}
		}, userID);

		// load interest tree
		JsonValue interestJson;
		Log.i(TAG, "Try loading interests from storage...");
		if((interestJson = FileApi.readJsonFromStorage("interests", this)) != null){
			if(interestJson.isArray()){
				mInterestTree = new InterestTree(interestJson.asArray());
				// if the other one finished first, create interest text views
				if(mUserInterests != null){
					createInterestViews();
				}
			}
		} else {
			// get list from server
			Log.i(TAG, "No files in storage available, try loading interests from server...");
			ServerConnector.getInterests(new ServerConnectorListener<JsonArray>() {

				@Override
				public void requestFinished(JsonArray json) {
					mInterestTree = new InterestTree(json);
					// if the other one finished first, create interest text views
					if(mUserInterests != null){
						createInterestViews();
					}
				}
				@Override
				public void requestError(ServerError error) {
					Log.e(TAG, error.getErrorMessage());
					Toast.makeText(getBaseContext(), "Error loading filters", Toast.LENGTH_LONG).show();
				}
			});
		}
	}

	@SuppressLint("UseSparseArrays")
	
	private void createInterestViews(){
		Log.d(TAG, "Create interest views...");

		/*
		 * first: as we only have the ids as an array we have to sort our which id
		 * is parent of which and how many views we are creating eventually.
		 * for every parent id we create one view with all its children attached.
		 * every parents has its own InterestTree. -> performance is not so important here
		 */

		// true := is parent; false := is child
		HashMap<Integer, Boolean> idMap = new HashMap<Integer, Boolean>();
		HashMap<Integer, InterestTree> interestTrees = new HashMap<Integer, InterestTree>();

		for (Integer interestId : mUserInterests) {
			InterestNode current = mInterestTree.find(interestId);
			if(current != null){
				idMap.put(interestId, !current.isLeaf());
			}
		}

		// create interest tree for every parent and sort our relations
		for (Map.Entry<Integer, Boolean> entry : idMap.entrySet()) {
			if(entry.getValue() && !interestTrees.containsKey(entry.getKey())){
				// if id is parent create new interest tree
				interestTrees.put(
						entry.getKey(), 
						new InterestTree(mInterestTree.find(entry.getKey()).copyNodeOnly()));
			} else if(!entry.getValue()) {
				//if id child add child to existing interest tree or create new interest tree if parent isnt already stored
				InterestNode child = mInterestTree.find(entry.getKey());
				if(child == null){
					continue; // skip if null
				}

				InterestNode parent = child.getParent();
				if(parent != null && !interestTrees.containsKey(parent.getInterestId())){
					// create new tree if parent doesnt already exist
					interestTrees.put(
							parent.getInterestId(), 
							new InterestTree(mInterestTree.find(parent.getInterestId()).copyNodeOnly()));
				}

				if(parent != null && interestTrees.containsKey(parent.getInterestId())){
					// parents exists and we add the child to the parent
					interestTrees.get(parent.getInterestId()).root
					.addChildren(child.copyNodeOnly());
				}
			}
		}

		// create views
		mUserInterestsMap.clear();
		mInterestContainer.removeAllViews();
		for (Map.Entry<Integer, InterestTree> entry : interestTrees.entrySet()) {
			final int tag = (int) System.currentTimeMillis();
			final InterestTree tree = entry.getValue();

			ExpandablePanel interestPanel = (ExpandablePanel) LayoutInflater.from(this).inflate(R.layout.interest_user_parent, null);
			((TextView) interestPanel.findViewById(R.id.interest_title)).setText(tree.root.getInterestName());

			// set edit button listener
			((TextView)interestPanel.findViewById(R.id.interest_edit)).setTypeface(ApplicationController.getTypeFace());
			((TextView)interestPanel.findViewById(R.id.interest_edit)).setText(R.string.fa_angle_double_down);
			

			for (InterestNode child : tree.root.getChildren()) {
				TextView childInterest = (TextView) LayoutInflater.from(this).inflate(R.layout.interest_user_child, null);
				childInterest.setText(child.getInterestName());
				((LinearLayout)interestPanel.findViewById(R.id.interest_children_conainer)).setVisibility(View.VISIBLE);
				((LinearLayout)interestPanel.findViewById(R.id.interest_children_conainer)).addView(childInterest);
			}


			// add tree ids to map to store separate interests
			mUserInterestsMap.put(tag, tree.getAllInterests());

			interestPanel.setHandleId(R.id.interest_title);
			interestPanel.setTag(tag); // set unique tag
			mInterestContainer.addView(interestPanel);
		}
	}
}
